package com.xuxueli.applyModules.utils.testcharts;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.plot.CenterTextMode;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.RingPlot;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.ui.HorizontalAlignment;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.data.general.DefaultPieDataset;
import org.springframework.core.io.ClassPathResource;
import sun.misc.BASE64Encoder;
import java.awt.*;
import java.io.*;
import java.util.List;
import java.util.*;

public class TestWordCharts {
    public static void main(String[] args) throws Exception {
        List<BarChartVO> barChartVOList = new ArrayList<>();
        for(int i=0; i<1; i++){
            BarChartVO vo = new BarChartVO();
            vo.setSeries("蓝色预警");
            vo.setValue(0.7);
            barChartVOList.add(vo);
        }
        BarChartVO vo1 = new BarChartVO();
        vo1.setSeries("");
        vo1.setValue(0.3);
        barChartVOList.add(vo1);

        generateRingChart(barChartVOList, "D:\\data\\11.jpg", 300, 300);

        Map<String, InputStream> params = new HashMap<>();
        params.put("warningRingBlueChart", new FileInputStream("D:\\data\\11.jpg"));
        //params.put("warningRingYellowChart", new FileInputStream("D:\\data\\11.jpg"));
        //params.put("warningRingOrangeChart", new FileInputStream("D:\\data\\11.jpg"));
        //params.put("warningRingRedChart", new FileInputStream("D:\\data\\11.jpg"));

        ClassPathResource resource = new ClassPathResource("Daytemplate.docx");
//        String templatePath="D:\\data\\Daytemplate.docx";
//        InputStream is=new FileInputStream(templatePath);
        InputStream is=resource.getInputStream();
        XWPFDocument docx=new XWPFDocument(is);
        WordUtils.insertImageData(docx, params);
        Map<String,String> map = new HashMap<>();
        map.put("reportDate", DateUtil.format(new Date()));
        map.put("所属功能区", "苏州银行");
        WordUtils.insertStringData(docx, map);
        Map<String, List<Map<String,String>>> stringListMap = new HashMap<>();
        List<Map<String,String>> mapList = new ArrayList<>();
        mapList.add(map);
        stringListMap.put("红色预警企业列表",mapList);
        WordUtils.insertWarningData(docx.getTables(), stringListMap);

        //输出
        OutputStream os=new FileOutputStream("D:\\data\\day.docx");
        docx.write(os);
        is.close();
        os.close();
        docx.close();

    }
    /**
     * 生成环状图
     *
     * @param barChartVOList
     * @param tempImgPath
     * @param width
     * @param height
     * @return
     */
    public static String generateRingChart(List<BarChartVO> barChartVOList, String tempImgPath, Integer width, Integer height) {
        DefaultPieDataset dataset = getDataSet3(barChartVOList);
        setTheme();
        JFreeChart chart = ChartFactory.createRingChart(
                "四色预警反馈率",
                dataset,
                true,
                false,
                false
        );
        equipRingContent(barChartVOList, chart);

        FileOutputStream fos_jpg = null;
        try {
            try {
                File outFile = new File(tempImgPath);
                if (!outFile.getParentFile().exists()) {
                    outFile.getParentFile().mkdirs();
                }
                fos_jpg = new FileOutputStream(tempImgPath);
                ChartUtils.writeChartAsJPEG(fos_jpg, 1.0f, chart, width, height, null);
            } catch (IOException e) {
            }
        } finally {
            try {
                fos_jpg.close();
            } catch (Exception e) {
            }
        }
        String result = getImageBase(tempImgPath);
        return result;
    }

    public static void equipRingContent(List<BarChartVO> barChartVOList, JFreeChart chart){
        RingPlot plot = (RingPlot) chart.getPlot();//获得图形面板
        plot.setIgnoreNullValues(true);  //忽略null值
        plot.setIgnoreZeroValues(false); //不忽略0值
        plot.setBackgroundPaint(Color.WHITE);//设置画布背景颜色
        plot.setOutlineVisible(false);//设置绘图区边框是否可见
        plot.setCenterText(String.valueOf(barChartVOList.get(0).getValue()));
        plot.setCenterTextMode(CenterTextMode.FIXED);
        //设置标签样式
        plot.setLabelFont(new Font("宋体", Font.BOLD, 20));
        plot.setSimpleLabels(false);
        plot.setLabelLinkPaint(Color.WHITE);
        plot.setLabelOutlinePaint(Color.WHITE);
        plot.setLabelLinksVisible(false);
        plot.setLabelShadowPaint(null);
        plot.setLabelOutlinePaint(new Color(0, true));
        plot.setLabelBackgroundPaint(new Color(0, true));
        plot.setLabelPaint(Color.WHITE);
        plot.setSeparatorPaint(Color.WHITE);
        plot.setShadowPaint(new Color(253, 253, 253));
        plot.setSectionDepth(0.35);
        plot.setStartAngle(90);
        plot.setDrawingSupplier(new DefaultDrawingSupplier(
                new Paint[]{
                        new Color(0, 153, 255),//超危颜色
                        new Color(192, 192, 192)
                },
                DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE,
                DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE,
                DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,
                DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE));
        plot.setSectionDepth(0.35);

        //图例样式的设定,图例含有M 和P 方法
        LegendTitle legendTitle = chart.getLegend();//获得图例标题
        legendTitle.setVisible(false); //原生的字体去掉
        //自定义文字内容
        TextTitle source1 = new TextTitle("蓝色预警 26次");
        TextTitle source2 = new TextTitle("平均反馈时长 50分钟");
        TextTitle source3 = new TextTitle("最长反馈时长 116分钟");
        source1.setFont(new Font( "SansSerif", Font.PLAIN,   13));
        source1.setPosition(RectangleEdge.BOTTOM);
        source1.setHorizontalAlignment(HorizontalAlignment.CENTER);

        source2.setFont(new Font( "SansSerif", Font.PLAIN,   13));
        source2.setPosition(RectangleEdge.BOTTOM);
        source2.setHorizontalAlignment(HorizontalAlignment.CENTER);

        source3.setFont(new Font( "SansSerif", Font.PLAIN,   13));
        source3.setPosition(RectangleEdge.BOTTOM);
        source3.setHorizontalAlignment(HorizontalAlignment.CENTER);
        chart.addSubtitle(0, source3);
        chart.addSubtitle(1, source2);
        chart.addSubtitle(2, source1);
        chart.setBackgroundPaint(Color.white);
        //标题的距离的设定
        TextTitle title = chart.getTitle();    //设置标题居左的距离
        title.setMargin(0, -20, 0, 0);//标题距离上下左右的距离
    }

    //获得图片的base64码
    public static String getImageBase(String src) {
        File file = new File(src);
        if (!file.exists()) {
            return "";
        }
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(file);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        try {
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        //删除临时文件
//        file.delete();
        return encoder.encode(data);
    }

    /**
     * <p>样式设定</p>
     */
    private static void setTheme() {
        //创建主题样式
        StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
        //设置标题
        standardChartTheme.setExtraLargeFont(new Font("隶书", Font.BOLD, 20));
        //设置图例的字体
        standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 15));
        //设置轴向的字体
        standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 15));
        ChartFactory.setChartTheme(standardChartTheme);
    }

    /*
     * 基本数据集
     */
    private static DefaultPieDataset getDataSet2(List<BarChartVO> barChartVOList) {
        DefaultPieDataset dataset = new DefaultPieDataset();
        for (BarChartVO bc : barChartVOList) {
            dataset.setValue(bc.getSeries(), bc.getValue());
        }
        return dataset;
    }

    private static DefaultPieDataset getDataSet3(List<BarChartVO> barChartVOList) {
        DefaultPieDataset dataset = new DefaultPieDataset();
        for (int i=0; i< barChartVOList.size(); i++) {
            dataset.insertValue(i, barChartVOList.get(i).getSeries(), barChartVOList.get(i).getValue());
        }
        return dataset;
    }
}